#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Arcadium.Graphics;
using Arcadium.Screens.Menus.MenuHelpers;
using Arcadium.Audio;
#endregion

namespace Arcadium
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    abstract class MenuScreen : GameScreen
    {
        #region Fields

        protected float menuEntryYstart = View.ScreenHeight / 3f;
        protected float menuEntryHeight = ViewResource.MenuFont.LineSpacing;

        private string menuTitle;

        private List<MenuEntry> menuEntries = new List<MenuEntry>();
        private int selectedEntry = 0;

        private Texture2D selectedEntryTexture;

        #endregion

        #region Properties


        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        }


        /// <summary>
        /// Gets or sets the selected menu entry, so derived classes 
        /// can control the selction.
        /// </summary>
        protected int SelectedEntry
        {
            get { return selectedEntry; }
            set { selectedEntry = value; }
        }


        /// <summary>
        /// TransitionDirection
        /// </summary>
        protected int TransitionDirection
        {
            get { return transitionDirection; }
            set
            {
                if (value != 1 || value != -1)
                    throw new ArgumentException();
                transitionDirection = value;
            }
        }

        private int transitionDirection = 1;


        #endregion

        #region Initialization

        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            this.menuTitle = menuTitle;

            TransitionOnTime = TimeSpan.FromSeconds(.25);
            TransitionOffTime = TimeSpan.FromSeconds(.25);
            AllowInputWhileTransitioning = false;
        }

        public override void LoadContent()
        {
            base.LoadContent();

            ContentManager content = ScreenManager.Game.Content;

            // TODO: Cat??
            selectedEntryTexture = content.Load<Texture2D>("cat"); //"Menu\\selectedEntryBackground");
        }

        #endregion

        #region Handle Input

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            // Move to the previous menu entry?
            if (input.IsMenuUp(ControllingPlayer))
            {
                AudioManager.MenuChangeItem.Play();
                selectedEntry--;

                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;
            }

            // Move to the next menu entry?
            if (input.IsMenuDown(ControllingPlayer))
            {
                AudioManager.MenuChangeItem.Play();
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;
            }

            // Accept or cancel the menu? We pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            PlayerIndex playerIndex;

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            {
                OnSelectEntry(selectedEntry, playerIndex);
            }
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            {
                OnCancel(playerIndex);
            }
        }

        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
        {
            AudioManager.MenuForward.Play();
            menuEntries[entryIndex].OnSelectEntry(playerIndex);
        }

        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel(PlayerIndex playerIndex)
        {
            AudioManager.MenuBack.Play();
            ExitScreen();
        }

        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, PlayerIndexEventArgs e)
        {
            OnCancel(e.PlayerIndex);
        }

        #endregion

        #region Update and Draw

        /// <summary>
        /// Allows the screen the chance to position the menu entries. By default
        /// all menu entries are lined up in a vertical list, centered on the screen.
        /// </summary>
        protected virtual void UpdateMenuEntryLocations()
        {
            // start at the bottom of the screen, each X value is generated per entry
            Vector2 position = new Vector2(0, menuEntryYstart);

            // update each menu entry's location in order
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];
                
                // TODO: each entry is to be centered horizontally trololol
                position.X = View.ScreenWidth / 3f;

                if (ScreenState == ScreenState.TransitionOn)
                    position.X += TransitionPosition * View.ScreenWidth * transitionDirection;
                else if (ScreenState == ScreenState.TransitionOff)
                    position.X -= TransitionPosition * View.ScreenWidth * transitionDirection;

                // set the entry's position
                menuEntry.Position = position;

                // move down for the next entry
                position.Y += menuEntryHeight;
            }

        }

        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        }

        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // make sure our entries are in the right place before we draw them
            UpdateMenuEntryLocations();

            SpriteBatch spriteBatch = ViewResource.SpriteBatch;
            SpriteFont font = ViewResource.MenuFont;

            spriteBatch.Begin();

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            if (!string.IsNullOrEmpty(menuTitle))
            {
                // Draw the menu title centered on the screen
                Vector2 titlePosition = new Vector2(View.ScreenWidth / 3,
                    View.ScreenHeight / 13 - transitionOffset * 100);
                Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
                Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
                spriteBatch.DrawString(font, menuTitle, View.Adjust(titlePosition), titleColor, 0,
                                       titleOrigin, View.ScreenScale, SpriteEffects.None, 0);
            }

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                //TODO: Texture for the selected menuentry. Keep this?
                if (isSelected)
                {
                    spriteBatch.Draw(selectedEntryTexture,
                        View.Adjust(menuEntry.Position),
                            null, Color.White, 0,
                        new Vector2(selectedEntryTexture.Width, 0) / 2,
                        View.ScreenScale, SpriteEffects.None, 0);
                }

                menuEntry.Draw(this, isSelected, gameTime);
            }

            spriteBatch.End();
        }

        #endregion
    }
}
